﻿using System;
using System.IO;
using System.Windows.Forms;

namespace SPDevExplorer
{
    public partial class DlgAddFiles : Form
    {
        public DlgAddFiles()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Get the ListView where files can be added
        /// </summary>
        public ListView ListOfFiles
        {
            get { return this.listViewFiles; }
        }

        public void AddFilesToListView(TreeNode folderNode)
        {
            ListView listView = ListOfFiles;
            FolderProperties fp = new FolderProperties(folderNode);
            if (fp.IsSystem)
            {
                MessageBox.Show("It is not possible to add files to a system folder", "Error");
                return;
            }

            string folderPath = SiteExplorer.EnsurePath(folderNode);
            if (!Directory.Exists(folderPath))
            {
                MessageBox.Show(
                    String.Format("The working folder '{0}' does not exist, does it contains no files to add",
                                  folderPath));
                return;
            }

            string[] files = Directory.GetFiles(folderPath);
            foreach (string file in files)
            {
                FileInfo fileInfo = new FileInfo(file);

                // Skip if file already in tree
                bool skip = false;
                foreach (TreeNode fileNode in folderNode.Nodes)
                {
                    if (String.Compare(fileNode.Text, fileInfo.Name, StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        skip = true;
                        break;
                    }
                }

                if (!skip)
                {
                    ListViewItem item = new ListViewItem(fileInfo.Name);
                    item.SubItems.Add(fileInfo.LastWriteTime.ToString());
                    item.SubItems.Add(fileInfo.Length.ToString());
                    listView.Items.Add(item);
                }
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void buttonSelectAll_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listViewFiles.Items)
            {
                item.Checked = true;
            }
        }

        private void buttonUnselectAll_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listViewFiles.Items)
            {
                item.Checked = false;
            }
        }
    }
}